package com.datawin.taotaocheche.base;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.jakewharton.rxbinding.view.RxView;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLayoutActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import com.datawin.taotaocheche.R;
import com.datawin.taotaocheche.comm.Constants;
import com.datawin.taotaocheche.event.LoginEvent;
import com.datawin.taotaocheche.event.NetErrorEvent;
import com.datawin.taotaocheche.util.AlertUtils;
import com.datawin.taotaocheche.util.LightStatusBarUtils;
import com.datawin.taotaocheche.util.RomUtils;
import com.datawin.taotaocheche.util.StringUtils;
import com.datawin.taotaocheche.util.ToastUtils;
import com.datawin.taotaocheche.util.UltimateBar;
import rx.functions.Action1;

/**
 * Created by JINAN on 2017/10/12.
 */

public abstract class BaseActivity extends AutoLayoutActivity {

    AlertDialog loading;
    int retryCount;
    AlertView operation;
    Toolbar toolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRoot();
        bind();
        setup();
        init(savedInstanceState);
    }

    protected void  setTitleBar(String color){
        UltimateBar ultimateBar = new UltimateBar(this);
        ultimateBar.setColorBar(Color.parseColor(color), false);
    }


    protected void setToolBar(@StringRes int res,String color) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        }
        if(!StringUtils.isEmpty(color)){
            toolbar.setBackgroundColor(Color.parseColor(color));
        }
        TextView title = (TextView) toolbar.findViewById(R.id.title);
        FrameLayout back = (FrameLayout) toolbar.findViewById(R.id.back);
        RxView.clicks(back)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        finishAct();
                    }
                });
        title.setText(res);
    }

    protected void setToolBar(String str,String color) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        }
        if(!StringUtils.isEmpty(color)){
            toolbar.setBackgroundColor(Color.parseColor(color));
        }
        TextView title = (TextView) toolbar.findViewById(R.id.title);
        FrameLayout back = (FrameLayout) toolbar.findViewById(R.id.back);
        RxView.clicks(back)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        finishAct();
                    }
                });
        title.setText(str);
    }

    protected abstract void setRoot();

    protected abstract void init(@Nullable Bundle savedInstanceState);

    protected void bind() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }
    /**
     * 依赖注入
     */
    protected void setup() {
    }



    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    /**
     * 网络出错处理
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetErrorEvent(NetErrorEvent event) {
        if (event.getLevel() > 0) { // 重连策略
            if (retryCount < 3) { // 限制3次
                onNetError(event);
                retryCount++;
            } else {
                loading(false);
                retryCount = 0;
            }
        } else {
            loading(false);
        }
    }

    protected abstract void onNetError(NetErrorEvent event);

    /**
     * 302跳转登录
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {

    }




    public void startActString(Class clz, String data) {
        Intent intent = new Intent(this, clz);
        if (data != null && !"".equals(data)) {
            intent.putExtra(Constants.KEYSTRING, data);
        }
        startActivity(intent);
    }

    public void startAct(Class clz, Serializable serializable) {
        Intent intent = new Intent(this, clz);
        if (serializable != null) {
            intent.putExtra(Constants.KEY, serializable);
        }
        startActivity(intent);
    }

    public void startAct(Intent intent) {
        startActivity(intent);
    }

    public void finishAct() {
        finish();
    }

    /**
     * 结束所有不含主页面
     */

    public void finishAllAct() {
        if (Constants.activitys.size() > 0) {
            for (Activity act :
                    Constants.activitys) {
                act.finish();

            }
            Constants.activitys.clear();
        }

    }

    /**
     * 结束注册登录
     */

    public void finishRegistetAct() {
        if (Constants.registerActivity.size() > 0) {
            for (Activity act :
                    Constants.registerActivity) {
                act.finish();

            }
            Constants.registerActivity.clear();
        }

    }


    public void showMsg(String msg) {
        ToastUtils.shortToast(msg);
    }

    public void loading(boolean isLoading) {
        if (isLoading) {
            if (loading == null) {
                loading = AlertUtils.loadingDialog(this);
            }
            if (!loading.isShowing()) {
                loading.show();
            }
        } else {
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
        }
    }

    public void operationing(String info) {
        if (operation == null) {
            operation = AlertUtils.checkWhat(this, new AlertUtils.AlertViewControl() {
                @Override
                public void onItemClickListener(int position) {
                    if (position == 0) {

                    } else if (position == 1) {

                    }

                }
            }, info);
            operation.show();
        }
    }

    public  void setStateText(){
        switch (RomUtils.getLightStatausBarAvailableRomType()) {
            case RomUtils.AvailableRomType.MIUI:
//                hintTv.setText("当前系统为MIUI6或以上 浅色状态栏可用");
                LightStatusBarUtils.setLightStatusBar(this, true);
                break;

            case RomUtils.AvailableRomType.FLYME:
//                hintTv.setText("当前系统为Flyme4或以上 浅色状态栏可用");
                LightStatusBarUtils.setLightStatusBar(this, true);
                break;

            case RomUtils.AvailableRomType.ANDROID_NATIVE:
//                hintTv.setText("当前系统为Android M或以上 浅色状态栏可用");
                LightStatusBarUtils.setLightStatusBar(this, true);
                break;

            case RomUtils.AvailableRomType.NA:
//                hintTv.setText("当前系统浅色状态栏不可用");
//                switchBtn.setEnabled(false);
//                switchBtn.setText("light status bar mode not available");
                LightStatusBarUtils.setLightStatusBar(this, false);
                break;
        }

    }


}
